module.exports = app => {
    const express = require('express')
    const router = express.Router({
        mergeParams: true //合并resource参数
    }) 

    //引用校验token
    const jwt = require('jsonwebtoken')

    const Cell = require('../models/Cell')
    const Floor = require('../models/Floor')
    const Money = require('../models/Money')
    const User = require('../models/User')
    const UserMoney = require('../models/UserMoney')
    const UserType = require('../models/UserType')
    const UserAdmin = require('../models/UserAdmin')

    //调用assert来返回错误
    const assert = require('http-assert')


    // 小区--------------------------------------------------------------------------------------------------

    router.post('/add_cell', async (request, response) => {
        let model = await Cell.create(request.body)
        response.send(model)
    });

    router.get('/cell_list', async (request, response) => {
        let cell_model = await Cell.find().populate("childFloor").lean();
        response.send(cell_model)
    });

    router.delete('/cell/:id', async (request, response) => {
        await Cell.findByIdAndDelete(request.params.id);
        response.send({
            success: true
        })
    });

    // 楼房--------------------------------------------------------------------------------------------------

    router.post('/add_floor', async (request, response) => {
        let model = await Floor.create(request.body)
        response.send(model)
    });

    router.get('/floor_list', async (request, response) => {
        //按照小区升序排列
        let cell_model = await Floor.find().sort({"parentCell":1}).populate("parentCell").lean();
        response.send(cell_model)
    });

    router.delete('/floor/:id', async (request, response) => {
        await Floor.findByIdAndDelete(request.params.id);
        response.send({
            success: true
        })
    });
    // 权限类别--------------------------------------------------------------------------------------------------

    router.post('/add_type', async (request, response) => {
        let model = await UserType.create(request.body)
        response.send(model)
    });

    router.get('/type_list', async (request, response) => {
        let cell_model = await UserType.find();
        response.send(cell_model)
    });

    router.delete('/type/:id', async (request, response) => {
        await UserType.findByIdAndDelete(request.params.id);
        response.send({
            success: true
        })
    });

    // 业主--------------------------------------------------------------------------------------------------

    router.post('/add_user', async (request, response) => {
        let model = await User.create(request.body)
        response.send(model)
    });

    router.get('/user_list', async (request, response) => {
        //排序：小区、楼号、房间号
        let cell_model = await User.find().sort({"parentCell":1}).sort({"parentFloor":1}).sort({"room":1}).populate("parentCell parentFloor user_type").lean();
        response.send(cell_model)
    });

    //编辑时获取信息
    router.get('/user_one/:id', async (request, response) => {
        let one_model = await User.findById(request.params.id).populate("parentCell parentFloor user_type").lean();
        response.send(one_model)
    });
    //编辑时提交信息
    router.put('/user_one/:id', async (request, response) => {
        let model = await User.findByIdAndUpdate(request.params.id, request.body);
        response.send(model)
    });

    router.delete('/user/:id', async (request, response) => {
        await User.findByIdAndDelete(request.params.id);
        response.send({
            success: true
        })
    });
    // 管理员--------------------------------------------------------------------------------------------------

    router.post('/add_admin', async (request, response) => {
        let model = await UserAdmin.create(request.body)
        response.send(model)
    });

    router.get('/admin_list', async (request, response) => {
        let cell_model = await UserAdmin.find().populate("type").lean();
        response.send(cell_model)
    });

    //编辑时获取信息
    router.get('/admin_one/:id', async (request, response) => {
        let one_model = await UserAdmin.findById(request.params.id);
        response.send(one_model)
    });
    //编辑时提交信息
    router.put('/admin_one/:id', async (request, response) => {
        let model = await UserAdmin.findByIdAndUpdate(request.params.id, request.body);
        response.send(model)
    });

    router.delete('/admin/:id', async (request, response) => {
        await UserAdmin.findByIdAndDelete(request.params.id);
        response.send({
            success: true
        })
    });

    // 费用设置--------------------------------------------------------------------------------------------------

    router.post('/add_money', async (request, response) => {
        let model = await Money.create(request.body)
        response.send(model)
    });

    router.get('/money_list', async (request, response) => {
        let model = await Money.find().populate("parentCell").lean();
        response.send(model)
    });


    //根据单元来选择金额
    router.get('/money_one/:id', async (request, response) => {
        let model = await Money.findOne({ parentCell:request.params.id});
        response.send(model)
    });

    router.put('/money/:id', async (request, response) => {
        let model = await Money.findByIdAndUpdate(request.params.id, request.body);
        response.send(model)
    });

    router.delete('/money/:id', async (request, response) => {
        await Money.findByIdAndDelete(request.params.id);
        response.send({
            success: true
        })
    });


    // 上缴费用的管理--------------------------------------------------------------------------------------------------
    router.post('/add_userMoney', async (request, response) => {
        let model = await UserMoney.create(request.body)
        response.send(model)
    });
    router.get('/userMoney_list', async (request, response) => {
        let model = await UserMoney.find().sort({"parentCell":1}).sort({"parentFloor":1}).populate("parentUser parentCell parentFloor").lean();
        response.send(model)
    });
    router.delete('/userMoney/:id', async (request, response) => {
        await UserMoney.findByIdAndDelete(request.params.id);
        response.send({
            success: true
        })
    });

    // 路由设置--------------------------------------------------------------------------------------------------

    // 登陆校验校验中间件
    const authMiddleware = async (request, response, next) => {

        const token = String(request.headers.authorization || '').split(' ').pop()
        assert(token, 401, '请先登陆')

        const {id} = jwt.verify(token, app.get('secret'))
        assert(token, 401, '请先登陆')

        //挂载到req表示请求的是谁
        request.user = await UserAdmin.findById(id)
        assert(request.user, 401, '请先登陆')

        next()
    }

    //统一路由的封装
    app.use('/admin/api/rest',authMiddleware, router)

   
    // 登陆路由
    app.post('/admin/api/login', async (request, response) => {
        
        //获取到的账号密码
        // console.log(request.body);
        
        const { account, password } = request.body
        // 1、根据用户名找用户
        // const AdminUser= require('../../models/AdminUser')
        const user = await UserAdmin.findOne({ account: account })

        assert(user, 422, '用户不存在')

        // 2、bcrypt校验密码,compareSync(明文, 密文)
        const isValid = require('bcrypt').compareSync(password, user.password)

        assert(isValid, 422, '密码错误')

        // 返回token
        // const jwt = require('jsonwebtoken')

        // 3、加密返回,get会和路由冲突，通过参数的情况让路由进行判断
        const token = jwt.sign({
            id: user._id,
        },app.get('secret'))

        response.send({
            token: token,
            username : user.name
        })
    })

     //错误处理4个参数
     app.use(async (err, request, response, next) => {
        response.status(err.statusCode || 500).send({
            message: err.message
        })
    })

}